import { addProject, fetchProjects } from '../../api/project';

Page({
  data: {
    projects: [],
    showModal: false,
    newProject: {
      id: 123,  // 假设用户的Id是123
      name: '',
    },
  },

  onLoad(options) {
    this.fetchProjects();
  },

  fetchProjects() {
    const { newProject } = this.data;
    const id = newProject.id;
    console.log('Fetching projects with Id:', id);
    fetchProjects({ Id: id }).then(response => {
      if (response.code === 1) {
        console.log('Projects fetched successfully:', response.data);
        this.setData({
          projects: response.data
        });
      } else {
        console.error('Failed to fetch projects');
      }
    }).catch(error => {
      console.error('Error fetching projects:', error);
    });
  },

  navigateToDetails(event) {
    const project = event.currentTarget.dataset.project;
    console.log('Navigating to details with project:', project);
    if (project && project.id) {
      console.log('Project ID:', project.id);
      console.log('Project Name:', project.name);
      wx.navigateTo({
        url: `/pages/Project-management/bigdetial/bigdetial?projectId=${project.id}&projectName=${project.name}`,
        events: {
          updateProjectList: this.fetchProjects // 注册事件更新项目列表
        }
      });
    } else {
      console.error('Project data is missing or invalid:', project);
    }
  },

  showAddProjectModal() {
    this.setData({
      showModal: true
    });
  },

  hideModal() {
    this.setData({
      showModal: false,
      newProject: {
        id: 123,  // 重置id为默认值
        name: '',
      }
    });
  },

  onInputChange(event) {
    const { value } = event.detail;
    this.setData({
      'newProject.name': value
    });
  },

  confirmAddProject() {
    const { newProject } = this.data;
    if (!newProject.name) {
      wx.showToast({
        title: '项目名称不能为空',
        icon: 'none'
      });
      return;
    }

    addProject({ name: newProject.name, Id: newProject.id }).then(response => {
      if (response.code === 1) {
        wx.showToast({
          title: '项目添加成功',
          icon: 'success'
        });
        this.hideModal();
        this.fetchProjects();
      } else {
        console.error('Failed to add project');
      }
    }).catch(error => {
      console.error('Error adding project:', error);
    });
  }
});
